package com.eprize;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.Timer;

public class GameViewer extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static ActionListener timer;
	private static JButton button;
	private static Timer t;
	public static void main(String[] args) {
		final BoardComponent game = new BoardComponent();
		final GameViewer gv = new GameViewer();

		class MouseClickListener extends MouseAdapter {
			public void mouseClicked(MouseEvent event) {
				int x = event.getX();
				int y = event.getY();

				game.initialize(x, y);
			}
		}

		MouseAdapter listener = new MouseClickListener();

		game.addMouseListener(listener);

		button = new JButton("Start");

		class MyMouseListener extends MouseAdapter {
			public void mouseClicked(MouseEvent me) {

				if (button.getText() == "Start") {
					timer = new TimerListener();

					final int DELAY = 100;
					t = new Timer(DELAY, timer);
					t.start();
					button.addActionListener(timer);
					game.generate();
					Component parent = (Component) me.getComponent()
							.getParent().getParent().getParent();
					parent.validate();
					parent.invalidate();
					parent.repaint();
					button.setText("Stop");
				} else if (button.getText() == "Stop") {
					t.stop();
					button.removeActionListener(timer);
					button.addActionListener(null);
					Component parent = (Component) me.getComponent()
							.getParent().getParent().getParent();
					parent.validate();
					parent.invalidate();
					parent.repaint();
					button.setText("Start");
				}
			}

			class TimerListener implements ActionListener {
				public void actionPerformed(ActionEvent event) {
					if (game.getBoardCount() > 0)
						game.generate();
					else
						button.removeActionListener(timer);
				}
			}
		}

		button.setLocation(250, 500);

		button.addMouseListener(new MyMouseListener());

		gv.setSize(600, 600);
		gv.setTitle("Life of Game");
		gv.setDefaultCloseOperation(EXIT_ON_CLOSE);
		gv.add(game);
		gv.add(button, BorderLayout.SOUTH);
		gv.setVisible(true);

	}

}
